package com.example.springbootwork.contorller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springbootwork.entity.User;
import com.example.springbootwork.mapper.UserMapper;
import com.example.springbootwork.service.impl.UserServiceImpl;
import com.example.springbootwork.util.Result;
import com.example.springbootwork.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserContorller {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/test")
    public List test(){
        List<User> list = userMapper.selectList(null);
        return list;
    }

    @PostMapping("/login")
    public Result<Object> login(@RequestParam("id") Integer id, @RequestParam("password") String password){
        String token;
        if(userService.verifyPassword(id, password)){
            token = tokenUtil.generateToken(userService.selectById(id));
            redisTemplate.opsForValue().set(token, id.toString());
            return Result.success(token);
        }
        return Result.fail();
    }

    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        if(redisTemplate.delete(token)){
            return Result.success();
        }
        else {
            return Result.fail();
        }
    }

    @GetMapping("/list")
    public Result<Map<String,Object>> getUserList(@RequestParam(value = "pageNo") Long pageNo, @RequestParam(value = "pageSize") Long pageSize){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(User::getId);
        Page<User> page = new Page<>(pageNo,pageSize);
        userService.page(page,wrapper);
        Map<String,Object> data = new HashMap<>();
        data.put("total",page.getTotal());
        data.put("rows",page.getRecords());
        return Result.success(data);
    }

    @GetMapping("/header")
    public String getHeaderInfo(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        return tokenUtil.parseToken(token).toString();
    }

}